package com.engine.jucailinkq.attendance.vacation.util;

import com.engine.jucailinkq.attendance.enums.*;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.jucailinkq.common.util.Utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.conn.RecordSetTrans;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class VocationCommonUtil {

    /**
     * 获得调整后的起算日期
     * @param qsrq 起算日期
     * @param dzqsrq 调整起算日期策略
     * @param fgrq 分割日期
     * @return
     */
    public static String getAfterAdjustTime(String qsrq,String dzqsrq,String fgrq){

        if (AdjustStartingTimeEnum.NEXT_MONTH.getKey().equals(dzqsrq)){
            String nextMonth = DateUtil.nextMonth(qsrq,1,DateUtil.yyyyMMdd);
            qsrq = nextMonth.split("-")[0]+"-"+nextMonth.split("-")[1]+"-01";

        }else if (AdjustStartingTimeEnum.BY_SEGMENT_TIME.getKey().equals(dzqsrq)){
            if (fgrq.length() == 1){
                fgrq = "0"+fgrq;
            }
            String divideDate=qsrq.split("-")[0]+"-"+qsrq.split("-")[1]+"-"+fgrq;
            if (DateUtil.getTime(qsrq).compareTo(DateUtil.getTime(divideDate)) >=0){
                //大于分割日期
                String nextMonth = DateUtil.nextMonth(qsrq,1,DateUtil.yyyyMMdd);
                qsrq = nextMonth.split("-")[0]+"-"+nextMonth.split("-")[1]+"-01";
            }else {
                //小于分割日期
                qsrq = qsrq.split("-")[0]+"-"+qsrq.split("-")[1]+"-01";
            }

        }else if (AdjustStartingTimeEnum.NOW_MONTH.getKey().equals(dzqsrq)){

            qsrq = qsrq.split("-")[0]+"-"+qsrq.split("-")[1]+"-01";
        }
        log.debug("getAfterAdjustTime qsrq : [{}]",qsrq);
        return qsrq;
    }

    /**
     * 获得执行日期
     * @param releaseDate  执行时间
     * @param vocationMap  假期集合
     * @return

    public static String getExcuteTime(String releaseDate ,Map<String,Object> vocationMap){
        String time = "";
        String edyxq = Util.null2String(vocationMap.get("edyxq"));
        String dqtqffts = Util.null2String(vocationMap.get("dqtqffts"));
        String ffdtffsj = Util.null2String(vocationMap.get("ffdtffsj"));
        String qsrq = Util.null2String(vocationMap.get("qsrq"));
        int edyxqsz = Double.valueOf(Util.null2String(vocationMap.get("edyxqsz"))).intValue();

        if (edyxq.equals(StartingUnitEnum.NATURAL_YEAR.getKey())){
            int nowYear = Integer.valueOf(releaseDate.split("-")[0])+1;
            int StartYear = Integer.valueOf(qsrq.split("-")[0]);
            if ((nowYear-StartYear)%edyxqsz == 0){
                String endYearTime = releaseDate.split("-")[0]+"-"+"12-31";
                time = DateUtil.beforeDay(endYearTime,Integer.valueOf(dqtqffts)) +" "+ffdtffsj;
            }
        }else if (edyxq.equals(StartingUnitEnum.STARTING_YEAR.getKey())){
            int betweenYear = DateUtil.getBetWeenYears(releaseDate.split(" ")[0],qsrq);
            if (betweenYear >=1 && betweenYear % edyxqsz == 0){
                if (betweenYear > 1){
                    String startTime = releaseDate.split("-")[0]+"-"+qsrq.split("-")[1]+"-"+qsrq.split("-")[2];
                    time = DateUtil.beforeDay(startTime,Integer.valueOf(dqtqffts)) +" "+ffdtffsj;
                }else {
                    String startTime = DateUtil.nextYear(qsrq,1,DateUtil.yyyyMMdd);
                    time = DateUtil.beforeDay(startTime,Integer.valueOf(dqtqffts)) +" "+ffdtffsj;
                }
            }
        }else if (edyxq.equals(StartingUnitEnum.NATURAL_MONTH.getKey())){
            String startTime = qsrq.split("-")[0]+"-"+qsrq.split("-")[1]+"-01";
            String nowTime = releaseDate.split("-")[0]+"-"+releaseDate.split("-")[1]+"-01";
            int betweenMonths = DateUtil.getBetWeenMonths(startTime,nowTime)+1;
            if (betweenMonths % edyxqsz == 0){
                int diffdays = DateUtil.getDays(releaseDate, Calendar.DAY_OF_MONTH);
                String endMonthTime = releaseDate.split("-")[0]+"-"+releaseDate.split("-")[1]+"-"+diffdays;
                time = DateUtil.beforeDay(endMonthTime,Integer.valueOf(dqtqffts)) +" "+ffdtffsj;
            }

        }else if (edyxq.equals(StartingUnitEnum.STARTING_MONTH.getKey())){

            String afterReleaseDate = DateUtil.AfterDay(releaseDate.split(" ")[0],Integer.valueOf(dqtqffts));
            int betweenMonths = DateUtil.getBetWeenMonths(qsrq,afterReleaseDate);
            if (betweenMonths >=1 && betweenMonths%edyxqsz == 0 && qsrq.split("-")[2].equals(afterReleaseDate.split("-")[2])){
                if (betweenMonths > 1){
                    String startTime = releaseDate.split(" ")[0];
                    time = startTime +" "+ffdtffsj;
                }else {
                    String startTime = DateUtil.nextMonth(qsrq,1,DateUtil.yyyyMMdd);
                    time = DateUtil.beforeDay(startTime,Integer.valueOf(dqtqffts)) +" "+ffdtffsj;
                }
            }

        }else if (edyxq.equals(StartingUnitEnum.NATURAL_WEEK.getKey())){
            int days = DateUtil.getBetWeenDays(qsrq,releaseDate.split(" ")[0]);
            int dayOfWeek = TimeUtil.getDayOfWeek(qsrq);
            if (dayOfWeek == 0){
                dayOfWeek = 7;
            }
            days = days-(7-dayOfWeek);
            int betWeenWeeks = days/7 +1;
            if (days % 7 == 0 && betWeenWeeks%edyxqsz == 0){
                String startTime = DateUtil.AfterDay(releaseDate.split(" ")[0],7);
                time = DateUtil.beforeDay(startTime,Integer.valueOf(dqtqffts)) +" "+ffdtffsj;
            }
        }else if (edyxq.equals(StartingUnitEnum.STARTING_WEEK.getKey())){
            String afterReleaseDate = DateUtil.AfterDay(releaseDate.split(" ")[0],Integer.valueOf(dqtqffts));
            int days = DateUtil.getBetWeenDays(qsrq,afterReleaseDate);
            int betWeenWeeks = days/7;
            if (days %7 ==0 && betWeenWeeks%edyxqsz == 0 && betWeenWeeks>=1){
                if (betWeenWeeks > 1){
                    String startTime = releaseDate.split(" ")[0];
                    time = startTime +" "+ffdtffsj;
                }else {
                    String startTime = DateUtil.AfterDay(qsrq,7);
                    time = DateUtil.beforeDay(startTime,Integer.valueOf(dqtqffts)) +" "+ffdtffsj;
                }
            }

        }else if (edyxq.equals(StartingUnitEnum.NATURAL_DAY.getKey())){
            time = releaseDate.split(" ")[0]+" "+ffdtffsj;
        }
        log.debug("excuteTime : [{}]",time);
        return time;
    }
     */

    /**
     * 根据依据字段和
     * @param vocationList 假期额度集合
     * @param intervalDuration 间隔时长
     * @param yjzd 依据字段
     * @return
     */
    public static Map<String,Object> getVocationMap(List<Map<String,Object>> vocationList,int intervalDuration,String yjzd,String userId){

        String edyj = Util.null2String(vocationList.get(0).get("edyj"));
        List<Map<String,Object>> resultList = Lists.newArrayList();
        if (edyj.equals("0")){
            resultList = vocationList.stream().filter(e ->  {
                //间隔时长起
                double jgsc0 = Util.null2String(e.get("jgsc0")).equals("")?0:Double.valueOf(Util.null2String(e.get("jgsc0")));
                //间隔时长止
                double jgsc1 = Util.null2String(e.get("jgsc1")).equals("")?0:Double.valueOf(Util.null2String(e.get("jgsc1")));
                if (intervalDuration >=jgsc0 && intervalDuration<=jgsc1){
                    return true;
                }else {
                    return false;
                }

            }).collect(Collectors.toList());
        }else if (edyj.equals("1")){
            //选项值
            if (!"".equals(yjzd)){
                resultList = vocationList.stream().filter(e ->  {
                    //选项值
                    int xxz = Double.valueOf(Util.null2String(e.get("xxz"))).intValue();
                    if (xxz == Double.valueOf(yjzd).intValue()){
                        return true;
                    }else {
                        return false;
                    }

                }).collect(Collectors.toList());
            }
        }else if (edyj.equals("2")){
            //选项值+间隔时长
            resultList = vocationList.stream().filter(e ->  {
                //间隔时长起
                double jgsc0 = Double.valueOf(Util.null2String(e.get("jgsc0")));
                //间隔时长止
                double jgsc1 = Double.valueOf(Util.null2String(e.get("jgsc1")));
                //选项值
                int xxz = Double.valueOf(Util.null2String(e.get("xxz")).toString()).intValue();
                if (!"".equals(yjzd) && xxz == Double.valueOf(yjzd).intValue() && intervalDuration >=jgsc0 && intervalDuration<=jgsc1){
                    return true;
                }else {
                    return false;
                }
            }).collect(Collectors.toList());
        }else if (edyj.equals("3")){
            //自由值
            resultList = vocationList.stream().filter(e->{
                List<String> zyzValue = (List<String>)e.get("zyzValue");
                return zyzValue.contains(userId);
            }).collect(Collectors.toList());

        }else if (edyj.equals("4")){
            //自由值+间隔时长
            resultList = vocationList.stream().filter(e->{
                List<String> zyzValue = (List<String>)e.get("zyzValue");
                //间隔时长起
                double jgsc0 = Double.valueOf(Util.null2String(e.get("jgsc0")));
                //间隔时长止
                double jgsc1 = Double.valueOf(Util.null2String(e.get("jgsc1")));

                if (intervalDuration >=jgsc0 && intervalDuration<=jgsc1 && zyzValue.contains(userId)){
                    return true;
                }else {
                    return false;
                }
            }).collect(Collectors.toList());
        }
        if (resultList.size() > 0){
            return resultList.get(0);
        }else {
            return new HashMap<>();
        }
    }

    /**
     * 计算额定休息天数
     * @param day  一年当中占据的天数
     * @param yearDay 一年的天数
     * @param ratedRestTime 额定可休时长
     * @param wscl 尾数处理
     * @return
     */
    public static double computeRestDays(int day,int yearDay,double ratedRestTime,String wscl){
        BigDecimal dayBig = new BigDecimal(day);
        BigDecimal yearDayBig = new BigDecimal(yearDay);
        BigDecimal ratedRestTimeBig = new BigDecimal(ratedRestTime);
        double result = 0;
        if (RemainderHandleEnum.ROUND_UP_FOUR.getKey().equals(wscl)){
            result = dayBig.multiply(ratedRestTimeBig).divide(yearDayBig,4,BigDecimal.ROUND_HALF_UP).doubleValue();
        }else if (RemainderHandleEnum.ROUND_UP_TWO.getKey().equals(wscl)){
            result = dayBig.multiply(ratedRestTimeBig).divide(yearDayBig,2,BigDecimal.ROUND_HALF_UP).doubleValue();
        }else if (RemainderHandleEnum.DOWN_ZERO_POINT_FIVE.getKey().equals(wscl)){
            result = dayBig.multiply(ratedRestTimeBig).divide(yearDayBig,2,BigDecimal.ROUND_HALF_UP).doubleValue();
            result = Math.floor(result * 2) / 2;
        }else if (RemainderHandleEnum.UP_ZERO_POINT_FIVE.getKey().equals(wscl)){
            result = dayBig.multiply(ratedRestTimeBig).divide(yearDayBig,2,BigDecimal.ROUND_HALF_UP).doubleValue();
            result = Math.ceil(result * 2) / 2;
        }else if (RemainderHandleEnum.ROUND_DOWN.getKey().equals(wscl)){
            result = dayBig.multiply(ratedRestTimeBig).divide(yearDayBig,0,BigDecimal.ROUND_DOWN).doubleValue();
        }else if (RemainderHandleEnum.ROUND_UP.getKey().equals(wscl)){
            result = dayBig.multiply(ratedRestTimeBig).divide(yearDayBig,0,BigDecimal.ROUND_UP).doubleValue();
        }

        return result;
    }
    public static double computeRestDays(int day,int yearDay,double ratedRestTime){
        BigDecimal dayBig = new BigDecimal(day);
        BigDecimal yearDayBig = new BigDecimal(yearDay);
        BigDecimal ratedRestTimeBig = new BigDecimal(ratedRestTime);
        double result = dayBig.multiply(ratedRestTimeBig).divide(yearDayBig,6,BigDecimal.ROUND_HALF_UP).doubleValue();
        return result;
    }
    public static double handleRestDays(double value,String wscl){
        double result = 0;
        if (RemainderHandleEnum.ROUND_UP_FOUR.getKey().equals(wscl)){
            result = new BigDecimal(value,new MathContext(4, RoundingMode.HALF_UP)).doubleValue();
        }else if (RemainderHandleEnum.ROUND_UP_TWO.getKey().equals(wscl)){
            result = new BigDecimal(value,new MathContext(2, RoundingMode.HALF_UP)).doubleValue();
        }else if (RemainderHandleEnum.DOWN_ZERO_POINT_FIVE.getKey().equals(wscl)){
            result = new BigDecimal(value,new MathContext(2, RoundingMode.HALF_UP)).doubleValue();
            result = Math.floor(result * 2) / 2;
        }else if (RemainderHandleEnum.UP_ZERO_POINT_FIVE.getKey().equals(wscl)){
            result = new BigDecimal(value,new MathContext(2, RoundingMode.HALF_UP)).doubleValue();
            result = Math.ceil(result * 2) / 2;
        }else if (RemainderHandleEnum.ROUND_DOWN.getKey().equals(wscl)){
            result = new BigDecimal(value).setScale(0,BigDecimal.ROUND_DOWN).doubleValue();
        }else if (RemainderHandleEnum.ROUND_UP.getKey().equals(wscl)){
            result = new BigDecimal(value).setScale(0,BigDecimal.ROUND_UP).doubleValue();
        }
        return result;
    }



    /**
     * 初始化插入假期余额参数
     * @param vocationMap 假期集合
     * @param userId 员工id
     * @param qsrq 起算日期
     * @param ffsj 发放时间
     * @return
     */
    public static Map<String,Object> getInsertHoliDayParam(Map<String,Object> vocationMap,String userId,String qsrq,String ffsj){
        Map<String,Object> param = Maps.newHashMap();

        //额度有效期间单位
        String edyxq = Util.null2String(vocationMap.get("edyxq"));
        //额度有效期间
        int edyxqsz = Double.valueOf(Util.null2String(vocationMap.get("edyxqsz"))).intValue();
        //提前执行发放操作的天数
        int dqtqffts = Integer.valueOf(Util.null2String(vocationMap.get("dqtqffts")));
        //结余未休处理
        String jywxcl = Util.null2String(vocationMap.get("jywxcl"));
        //延期时长
        String yqsc = Util.null2String(vocationMap.get("yqsc"));
        //执行发放的时间点
        String ffdtffsj = Util.null2String(vocationMap.get("ffdtffsj"));

        param.put("lyid",vocationMap.get("dataid"));
        param.put("jqid",vocationMap.get("jb"));
        param.put("ygid",userId);
        param.put("qsrq",qsrq);
        param.put("ffsj",ffsj);

        if (edyxq.equals(StartingUnitEnum.NATURAL_YEAR.getKey())){
            String nowEndYearTime = ffsj.split("-")[0]+"-12-31";
            String forWardTime = DateUtil.beforeDay(nowEndYearTime,dqtqffts) +" "+ffdtffsj;
            if (DateUtil.getTime(ffsj).compareTo(DateUtil.getTime(forWardTime)) >=0){
                //发放下一年
                String nextYear = DateUtil.nextYear(ffsj,1,DateUtil.yyyyMMdd);
                String jzrq = DateUtil.nextYear(nextYear,edyxqsz-1,DateUtil.yyyyMMdd);
                param.put("sxrq",nextYear.split("-")[0]+"-01-01");
                param.put("jzrq",jzrq.split("-")[0]+"-12-31");
            }else {
                //发放当年
                param.put("sxrq",ffsj.split("-")[0]+"-01-01");
                param.put("jzrq",DateUtil.nextYear(ffsj.split("-")[0]+"-12-31",edyxqsz-1,DateUtil.yyyyMMdd));
            }

        }else if (edyxq.equals(StartingUnitEnum.STARTING_YEAR.getKey())){
            String startTime = ffsj.split("-")[0]+"-"+qsrq.split("-")[1]+"-"+qsrq.split("-")[2];
            String beforeStartTime = DateUtil.beforeYear(startTime,1,DateUtil.yyyyMMdd);
            String beforeEndTime = DateUtil.beforeDay(startTime,1);
            String endTime = DateUtil.nextYear(beforeEndTime,1,DateUtil.yyyyMMdd);
            String forWardTime = DateUtil.beforeDay(beforeEndTime,dqtqffts) +" "+ffdtffsj;

            if (DateUtil.getTime(ffsj).compareTo(DateUtil.getTime(forWardTime)) >=0){
                //发放下一周期
                param.put("sxrq",startTime);
                param.put("jzrq",DateUtil.nextYear(endTime,edyxqsz-1,DateUtil.yyyyMMdd));
            }else {
                //发放当前周期
                param.put("sxrq",beforeStartTime);
                param.put("jzrq",DateUtil.nextYear(beforeEndTime,edyxqsz-1,DateUtil.yyyyMMdd));
            }

        }else if (edyxq.equals(StartingUnitEnum.NATURAL_MONTH.getKey())){
            String sxrq = DateUtil.nextMonth(ffsj,1,DateUtil.yyyyMM)+"-01";
            int days = DateUtil.getDays(sxrq,Calendar.DAY_OF_MONTH);
            String jzrq = DateUtil.nextMonth(sxrq,edyxqsz-1,DateUtil.yyyyMM) +"-"+days;

            String beforeSxrq = ffsj.split("-")[0]+"-"+ffsj.split("-")[1]+"-01";
            int beforeDays = DateUtil.getDays(beforeSxrq,Calendar.DAY_OF_MONTH);
            String beforeJzrq = DateUtil.nextMonth(beforeSxrq,edyxqsz-1,DateUtil.yyyyMM);
            int beforeJzrqDays = DateUtil.getDays(beforeJzrq,Calendar.DAY_OF_MONTH);
            beforeJzrq = beforeJzrq +"-"+beforeJzrqDays;

            String forWardTime = DateUtil.beforeDay(ffsj.split("-")[0]+"-"+ffsj.split("-")[1]+"-"+beforeDays,dqtqffts)+" "+ffdtffsj;

            if (DateUtil.getTime(ffsj).compareTo(DateUtil.getTime(forWardTime)) >=0){
                //发放下一月份
                param.put("sxrq",sxrq);
                param.put("jzrq",jzrq);
            }else {
                //发放当前月份
                param.put("sxrq",beforeSxrq);
                param.put("jzrq",beforeJzrq);
            }

        }else if (edyxq.equals(StartingUnitEnum.STARTING_MONTH.getKey())){
            String sxrq = ffsj.split("-")[0]+"-"+ffsj.split("-")[1]+"-"+qsrq.split("-")[2];
            String beforeEndTime = DateUtil.beforeDay(sxrq,1);
            String beforeSxrq = DateUtil.beforeMonth(sxrq,1);
            String beforeJzrq = DateUtil.nextMonth(beforeEndTime,edyxqsz-1,DateUtil.yyyyMMdd);
            String jzrq = DateUtil.nextMonth(beforeEndTime,edyxqsz,DateUtil.yyyyMMdd);

            String forWardTime = DateUtil.beforeDay(beforeEndTime,dqtqffts)+" "+ffdtffsj;

            if (DateUtil.getTime(ffsj).compareTo(DateUtil.getTime(forWardTime)) >=0){
                //发放下一月份
                param.put("sxrq",sxrq);
                param.put("jzrq",jzrq);
            }else {
                //发放当前月份
                param.put("sxrq",beforeSxrq);
                param.put("jzrq",beforeJzrq);
            }

        }else if (edyxq.equals(StartingUnitEnum.NATURAL_WEEK.getKey())){
            int dayOfWeek = TimeUtil.getDayOfWeek(ffsj);
            if (dayOfWeek == 0){
                dayOfWeek = 7;
            }
            String time = ffsj.split(" ")[0];
            String sxrq = DateUtil.AfterDay(time,8-dayOfWeek);
            String beforeSxrq = DateUtil.beforeDay(time,dayOfWeek-1);
            String beforeJxrq = DateUtil.AfterDay(time,8-dayOfWeek);

            String forWardTime = DateUtil.beforeDay(beforeJxrq,dqtqffts)+" "+ffdtffsj;

            if (DateUtil.getTime(ffsj).compareTo(DateUtil.getTime(forWardTime)) >=0){
                //发放下一周
                param.put("sxrq",sxrq);
                param.put("jzrq",DateUtil.AfterDay(sxrq,7*edyxqsz-1));
            }else {
                //发放当前周
                param.put("sxrq",beforeSxrq);
                param.put("jzrq",DateUtil.AfterDay(beforeSxrq,7*edyxqsz-1));
            }

        }else if (edyxq.equals(StartingUnitEnum.STARTING_WEEK.getKey())){

            String time = ffsj.split(" ")[0];
            int days = DateUtil.getBetWeenDays(qsrq,time)+1;
            int residueDays = days%7;
            String beforeSxrq = DateUtil.beforeDay(time,residueDays);
            String beforeEndTime = DateUtil.AfterDay(beforeSxrq,6);
            String sxrq = DateUtil.AfterDay(beforeSxrq,7);

            String forWardTime = DateUtil.beforeDay(beforeEndTime,dqtqffts)+" "+ffdtffsj;

            if (DateUtil.getTime(ffsj).compareTo(DateUtil.getTime(forWardTime)) >=0){
                //发放下一周周期
                param.put("sxrq",sxrq);
                param.put("jzrq",DateUtil.AfterDay(sxrq,7*edyxqsz-1));
            }else {
                //发放当前周期
                param.put("sxrq",beforeSxrq);
                param.put("jzrq",DateUtil.AfterDay(beforeSxrq,7*edyxqsz-1));
            }

        }else if (edyxq.equals(StartingUnitEnum.NATURAL_DAY.getKey())){
            String sxrq = DateUtil.AfterDay(ffsj.split(" ")[0],0);
            param.put("sxrq",sxrq);
            param.put("jzrq",sxrq);
        }

        if (BalanceHandleEnum.DELAY.getKey().equals(jywxcl)){
            if (DelayTypeEnum.ONE_MONTH.getKey().equals(yqsc)){
                //一个月
                param.put("yqsxrq",DateUtil.nextMonth(param.get("jzrq").toString(),1,DateUtil.yyyyMMdd));
            }else if (DelayTypeEnum.TWO_MONTH.getKey().equals(yqsc)){
                //两个月
                param.put("yqsxrq",DateUtil.nextMonth(param.get("jzrq").toString(),2,DateUtil.yyyyMMdd));
            }else if (DelayTypeEnum.THREE_MONTH.getKey().equals(yqsc)){
                //三个月
                param.put("yqsxrq",DateUtil.nextMonth(param.get("jzrq").toString(),3,DateUtil.yyyyMMdd));
            }else if (DelayTypeEnum.HALF_YEAR.getKey().equals(yqsc)){
                //半年
                param.put("yqsxrq",DateUtil.nextMonth(param.get("jzrq").toString(),6,DateUtil.yyyyMMdd));
            }else if (DelayTypeEnum.ONE_YEAR.getKey().equals(yqsc)){
                //一年
                param.put("yqsxrq",DateUtil.nextMonth(param.get("jzrq").toString(),12,DateUtil.yyyyMMdd));
            }
        }
        return param;
    }

    /**
     * 更新假期余额
     * @param tableName 假期余额表名
     * @param dataMap  参数
     */
    public static void updateHolidayBalance(String tableName,Map<String,Object> dataMap,List<Map<String,Object>> dataList,String edyxq){
        log.debug("updateHolidayBalance dataMap:[{}]",dataMap);
        try {

            String lyid = Util.null2String(dataMap.get("lyid"));
            String ygid = Util.null2String(dataMap.get("ygid"));
            String jqid = Util.null2String(dataMap.get("jqid"));
            String sxrq = Util.null2String(dataMap.get("sxrq"));
            String jzrq = Util.null2String(dataMap.get("jzrq"));
            dataMap.put("yxsc",0);
            dataMap.put("ztsc",0);
            dataMap.put("wxsc",dataMap.get("ktsc"));
            dataMap.put("yqsxrq",dataMap.get("jzrq"));
            dataMap.put("jxsc",0);
            dataMap.put("yqsc",0);
            dataMap.put("yqyxsc",0);
            dataMap.put("zfsc",0);
            //查询上一笔假期余额是否有透支情况
            String queryBeforeHolidaySql = "select id,yxsc,wxsc,ktsc,ztsc,zfsc,modedatacreatedate,modedatacreatetime from uf_jcl_kq_jqye where  ygid=? and jqid=? order by modedatacreatedate desc ,modedatacreatetime desc";
            String beforeSxrq = "";
            String beforeJzrq = "";
            if (edyxq.equals(StartingUnitEnum.NATURAL_YEAR.getKey()) || edyxq.equals(StartingUnitEnum.STARTING_YEAR.getKey())){
                beforeSxrq = DateUtil.beforeYear(sxrq,1,DateUtil.yyyyMMdd);
                beforeJzrq = DateUtil.beforeYear(jzrq,1,DateUtil.yyyyMMdd);
            }else if (edyxq.equals(StartingUnitEnum.NATURAL_MONTH.getKey()) || edyxq.equals(StartingUnitEnum.STARTING_MONTH.getKey())){
                beforeSxrq = DateUtil.beforeMonth(sxrq,1);
                beforeJzrq = DateUtil.beforeMonth(jzrq,1);
            }else if (edyxq.equals(StartingUnitEnum.NATURAL_WEEK.getKey()) || edyxq.equals(StartingUnitEnum.STARTING_WEEK.getKey())){
                beforeSxrq = DateUtil.beforeDay(sxrq,7);
                beforeJzrq = DateUtil.beforeDay(jzrq,7);
            }else if (edyxq.equals(StartingUnitEnum.NATURAL_DAY.getKey())){
                beforeSxrq = DateUtil.beforeDay(sxrq,1);
                beforeJzrq = DateUtil.beforeDay(jzrq,1);
            }
            List<Map<String,Object>> beforeHolidayBalanceList = DbTools.getSqlToList(queryBeforeHolidaySql,ygid,jqid);
            double beforewxsc = 0;

            boolean excuteResult = false;
            if (dataList.size()>0){
                Map<String,Object> condition = Maps.newHashMap();
                condition.put("id",dataList.get(0).get("id"));
                double ktsc = Double.valueOf(dataMap.get("ktsc").toString());
                double oldyxsc = Double.valueOf(Util.null2String(dataList.get(0).get("yxsc")).equals("")?"0":Util.null2String(dataList.get(0).get("yxsc")));
                double oldztsc = Double.valueOf(Util.null2String(dataList.get(0).get("ztsc")).equals("")?"0":Util.null2String(dataList.get(0).get("ztsc")));
                double oldzfsc = Double.valueOf(Util.null2String(dataList.get(0).get("zfsc")).equals("")?"0":Util.null2String(dataList.get(0).get("zfsc")));
                double oldjxsc = Double.valueOf(Util.null2String(dataList.get(0).get("jxsc")).equals("")?"0":Util.null2String(dataList.get(0).get("jxsc")));
                dataMap.put("yqsc",dataList.get(0).get("yqsc"));
                dataMap.put("yqyxsc",dataList.get(0).get("yqyxsc"));
                dataMap.put("jxsc",oldjxsc);
                dataMap.put("ztsc",oldztsc);
                dataMap.put("zfsc",oldzfsc);
                double wxsc = VocationCommonUtil.substract(dataMap.get("ktsc").toString(),oldztsc,oldzfsc,oldyxsc);
//            if (beforewxsc < 0){
//                wxsc = wxsc+beforewxsc;
//                oldyxsc = oldyxsc-beforewxsc;
//            }
                dataMap.put("yxsc",oldyxsc);
                dataMap.put("wxsc",String.format ("%.2f",wxsc));
                excuteResult = DbTools.update(CommonUtil.makeUpdateSql(tableName,dataMap,condition));
            }else {
                if (beforeHolidayBalanceList.size() > 0 && Double.valueOf(beforeHolidayBalanceList.get(0).get("wxsc").toString()) <0){
                    //beforeHolidayBalanceList
                    beforewxsc = Double.valueOf(beforeHolidayBalanceList.get(0).get("wxsc").toString());

                }
                if (beforewxsc < 0){
                    dataMap.put("wxsc",Double.valueOf(dataMap.get("ktsc").toString())+beforewxsc);
                    dataMap.put("yxsc",0-beforewxsc);
                }
                excuteResult = Utils.InsertFormTable(tableName, dataMap, Utils.getFormmodeIdMap());
                String querNowSql = "select id,yxsc,wxsc,ktsc from uf_jcl_kq_jqye where lyid=? and ygid=? and jqid=? and sxrq=? and jzrq=? and (lylx is null or  lylx = 6) order by modedatacreatedate desc ,modedatacreatetime desc";
                dataList = DbTools.getSqlToList(querNowSql,lyid,ygid,jqid,dataMap.get("sxrq"),dataMap.get("jzrq"));
                if (excuteResult && beforewxsc <0){
                    handleOverdraftHoliday(beforeHolidayBalanceList.get(0),beforewxsc,dataList.get(0));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }


    }

    /**
     * 该周期是否已存在
     * @param tableName
     * @param dataMap
     * @return
     */
    public static List<Map<String,Object>> ifexist(String tableName,Map<String,Object> dataMap){
        log.debug("ifexist dataMap:[{}]",dataMap);
        String lyid = Util.null2String(dataMap.get("lyid"));
        String ygid = Util.null2String(dataMap.get("ygid"));
        String jqid = Util.null2String(dataMap.get("jqid"));
        String sxrq = Util.null2String(dataMap.get("sxrq"));
        String jzrq = Util.null2String(dataMap.get("jzrq"));
        String sql = "select id,ffsj,ktsc,yxsc,wxsc,ztsc,zfsc,yqsc,yqyxsc,yqsxrq from "+tableName +" where lyid=? and ygid=? and jqid=? and sxrq>=? and jzrq<=?";
        List<Map<String,Object>> dataList = DbTools.getSqlToList(sql,lyid,ygid,jqid,sxrq,jzrq);

        return dataList;
    }

    /**
     * 处理透支余额
     */
    public static void handleOverdraftHoliday(Map<String,Object> beforeHolidayBalance, double beforewxsc, Map<String,Object> nowData)throws Exception{

        String updatesql = "update uf_jcl_kq_jqye set wxsc=0,yxsc=? where id=?";

        double oldktsc = Double.valueOf(beforeHolidayBalance.get("ktsc").toString());
        double oldztsc = Double.valueOf(Util.null2String(beforeHolidayBalance.get("ztsc")).equals("")?"0":Util.null2String(beforeHolidayBalance.get("ztsc")));
        double oldzfsc = Double.valueOf(Util.null2String(beforeHolidayBalance.get("zfsc")).equals("")?"0":Util.null2String(beforeHolidayBalance.get("zfsc")));
        //上一笔假透支归0
        double oldyxsc = new BigDecimal(oldktsc).subtract(new BigDecimal(oldztsc)).subtract(new BigDecimal(oldzfsc),new MathContext(2, RoundingMode.HALF_UP)).doubleValue();

        DbTools.update(updatesql,oldyxsc,beforeHolidayBalance.get("id"));

        //修改请假申请明细的假期余额字段将透支的假改成当前的
        String currentHolidayId = nowData.get("id").toString();

        String beforeHolidayId = beforeHolidayBalance.get("id").toString();

        String sql = "select id,glrq,sysc,mainid,glmxid,jqye,mxid from uf_jcl_kq_qjjl_dt2 where jqye=? order by id desc";
        List<Map<String,Object>> askforleaveList = DbTools.getSqlToList(sql,beforeHolidayId);
        BigDecimal overdraftHoliday = new BigDecimal(String.valueOf(Math.abs(beforewxsc)));
        List<String> ids = Lists.newArrayList();
        for (Map<String,Object> askforleave:askforleaveList){
            BigDecimal sysc = new BigDecimal(askforleave.get("sysc").toString());
            overdraftHoliday = overdraftHoliday.subtract(sysc,new MathContext(2, RoundingMode.HALF_UP));
            if (overdraftHoliday.doubleValue() >= 0){
                ids.add(askforleave.get("id").toString());
            }else {
                double newsysc = Math.abs(overdraftHoliday.doubleValue());
                overdraftHoliday = overdraftHoliday.add(sysc);
                String updateSql = "update uf_jcl_kq_qjjl_dt2 set sysc=? where id=?";
                Map<String,Object> insertParam = Maps.newHashMap();
                insertParam.put("mainid",askforleave.get("mainid"));
                insertParam.put("glmxid",askforleave.get("glmxid"));
                insertParam.put("jqye",currentHolidayId);
                insertParam.put("sysc",overdraftHoliday.doubleValue());
                insertParam.put("glrq",askforleave.get("glrq"));
                insertParam.put("mxid",askforleave.get("mxid"));
                if (DbTools.update(updateSql,newsysc,askforleave.get("id"))){
                    Utils.InsertFormTable("uf_jcl_kq_qjjl_dt2",insertParam,Utils.getFormmodeIdMap());
                }
                break;
            }
        }
        log.debug("need adjust askforleave detail2 data : [{}]",ids);
        if (ids.size() > 0){
            updatesql = "update uf_jcl_kq_qjjl_dt2 set jqye=? where id in ("+String.join(",",ids)+")";
            DbTools.update(updatesql,currentHolidayId);
        }
    }
    public static double substract(String total,Object...values){
        BigDecimal totalbig = new BigDecimal(total);
        for (Object value :values){
            totalbig = totalbig.subtract(new BigDecimal(String.valueOf(value)),new MathContext(4, RoundingMode.HALF_UP));
        }
        return totalbig.doubleValue();
    }
}
